package com.imddy.gkrpc.server;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.imddy.gkrpc.Request;
import com.imddy.gkrpc.ServiceDescriptor;
import com.imddy.gkrpc.common.utils.ReflectionUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 管理RPC暴露的服务
 * @author Administrator
 *
 */
@Slf4j
public class ServiceManager {
	private Map<ServiceDescriptor, ServiceInstance> services;
	
	public ServiceManager() {
		this.services = new ConcurrentHashMap<ServiceDescriptor, ServiceInstance>();
	}
	
	public <T> void registe(Class<T> interfaceClass, T bean) {
		Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
		for (Method method : methods) {
			ServiceInstance sis = new ServiceInstance(bean, method);
			ServiceDescriptor sdp = ServiceDescriptor.from(interfaceClass, method);
			
			services.put(sdp, sis);
			log.info("register service: {} {} ", sdp.getClazz(), sdp.getMethod());
		}
	}
	
	
	public ServiceInstance lookup(Request request) {
		ServiceDescriptor sdp = request.getService();
		return services.get(sdp);
	}
}
